// V-admin/src/api/request.ts
import axios from 'axios';

const request = axios.create({
  baseURL: 'http://localhost:3000/api',
  timeout: 10000,
});

// 请求拦截器 - 修复token名称
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token'); // 改为 token，不是 admin_token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
      console.log('🔐 API请求携带Token:', token.substring(0, 20) + '...');
    } else {
      console.warn('⚠️ API请求未找到token');
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.error('❌ API请求错误:', error.response?.status, error.response?.data);
    if (error.response?.status === 401) {
      console.log('🔐 Token无效，清除登录信息');
      localStorage.removeItem('token');
      localStorage.removeItem('userType');
      localStorage.removeItem('userInfo');
      window.location.href = 'http://localhost:5173/login';
    }
    return Promise.reject(error);
  }
);

export default request;